from django.core.management.base import BaseCommand
from cmdb.views import host_monitor


class Command(BaseCommand):
    help = '启动主机状态监控服务'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('正在启动主机状态监控服务...'))
        
        try:
            host_monitor.start_monitoring()
            self.stdout.write(
                self.style.SUCCESS('主机状态监控服务启动成功！')
            )
            self.stdout.write('监控服务将每30秒检测一次所有主机状态')
            
            # 保持服务运行
            import time
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                self.stdout.write('\n正在停止监控服务...')
                host_monitor.stop_monitoring()
                self.stdout.write(
                    self.style.SUCCESS('主机状态监控服务已停止')
                )
                
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'启动监控服务失败: {e}')
            )
